package cn.jhz.learn.community_dynamic.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jhz.learn.community_dynamic.common.util.RequestHelper;
import cn.jhz.learn.community_dynamic.dao.PermissionJpaRepository;
import cn.jhz.learn.community_dynamic.model.AclEntity;
import cn.jhz.learn.community_dynamic.vo.app.AclView;
import cn.jhz.learn.community_dynamic.vo.wbms.ColumnType;

@Service
public class PermissionManager {
    private final PermissionJpaRepository permissionJpaRepository;

    @Autowired
    public PermissionManager(PermissionJpaRepository permissionJpaRepository) {
	super();
	this.permissionJpaRepository = permissionJpaRepository;
    }
    
    public AclEntity newInstanceByPermission(AclView permission) {
	return AclEntity.builder().name(permission.getName()).type(permission.getType()).status(permission.getStatus()).parentId(permission.getParentId()).resource(permission.getResource()).build();
    }
    
    @Transactional
    public AclEntity addInstance(AclEntity entity) {
	return this.permissionJpaRepository.save(entity);
    }
    
    @Transactional
    public AclEntity updataByPermission(AclView permission) {
	// TODO 后期添加缺值处理
	AclEntity entity = this.permissionJpaRepository.findById(permission.getId()).get();
	
	for (Object columnType : RequestHelper.getPatchColumns()) {
	    switch ((ColumnType) columnType) {
	    case NAME:
		entity.setName(permission.getName());
		break;
	    case PARENT_ID:
		entity.setParentId(permission.getParentId());
		break;
	    case RESOURCE:
		entity.setResource(permission.getResource());
		break;
	    case STATUS:
		permissionJpaRepository.setFixedStatusFor(permission.getStatus(), permission.getId());
		break;
	    case TYPE:
		entity.setType(permission.getType());
		break;
	    case SEQ:
		entity.setSeq(permission.getSeq());
		break;
	    default:
		break;
	    }
	}
	return entity;
    }
}
